/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: 北京银杉金服科技有限公司
 * 系统版本: 1.0.0
 * 开发人员: zhangfb
 * 开发时间: 2018/9/11 21:17
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.hyacinth.service.impl;

import com.hyacinth.constant.ErrorCodeEnum;
import com.hyacinth.constant.IDict;
import com.hyacinth.dto.UserDto;
import com.hyacinth.entity.User;
import com.hyacinth.exception.BusinessException;
import com.hyacinth.repository.jpa.UserRepository;
import com.hyacinth.service.UserService;
import com.hyacinth.util.BeanUtils;
import com.hyacinth.util.JsonMapper;
import com.hyacinth.util.generator.CodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import javax.validation.constraints.NotNull;

/**
 * 用户服务类
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
@Slf4j
@Service
@Transactional
public class UserServiceImpl implements UserService{

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public UserServiceImpl(UserRepository userRepository,
                           PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    private User findByUserName(@NotNull String userName) {
        return userRepository.findByName(userName);
    }

    @Override
    public User findByUserName(@NotNull String userName, @NotNull String dataFlag) {
        return userRepository.findByNameAndDataFlag(userName, dataFlag);
    }

    @Override
    public User save(UserDto userDto) {
        User user = findByUserName(userDto.name);
        if (user != null) {
            if (!IDict.dataFlag_OK.equals(user.getDataFlag())) {
                log.info("用户信息已存在，已将删除状态改为正常状态，用户名称={}",user.getName());
                user.setDataFlag(IDict.dataFlag_OK);
                return userRepository.save(user);
            }
            throw new BusinessException(ErrorCodeEnum.GL99990006);
        }
        user = new User();
        user.setCode(CodeUtils.getCode(User.class));
        try {
            BeanUtils.copyAllProperties(userDto, user);
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeEnum.GL99990004, JsonMapper.toJsonString(userDto),JsonMapper.toJsonString(user));
        }
        // 设置密码
        user.setPassWord(passwordEncoder.encode(userDto.passWord));
        return userRepository.save(user);
    }
}
